package com.wondersgroup.app.util;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.wondersgroup.core.frame.TraceException;

import java.util.HashSet;
import java.util.Set;

/**
 * 登录和权限控制相关方法拦截器
 *
 * @author mengke
 */
public class AccessControlMethodInterceptor implements MethodInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(AccessControlMethodInterceptor.class);

    @Autowired
    private HttpSession session;

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        logger.debug("~~~~~~~~ enter AccessControlMethodInterceptor ~~~~~~~~");
        try {
            long begin = System.currentTimeMillis();

            boolean isValid = false;
            if (invocation.getMethod().isAnnotationPresent(LoginRequired.class)) {
                isValid = loginRequiredHandler();
            } else if (invocation.getMethod().isAnnotationPresent(HasPermission.class)) {
                HasPermission p = invocation.getMethod().getAnnotation(HasPermission.class);
            	isValid = hasPermissionHandler(p.value());
            }

            long useTime = System.currentTimeMillis() - begin;
            logger.debug("~~~~~~~~ AccessControlMethodInterceptor useTime:" + useTime + "~~~~~~~~");

            //如果没有通过权限控制，则返回access denied
            if (!isValid) {
                throw TraceException.returnException("012010");
            } else {//通过权限控制，则继续执行方法调用
                begin = System.currentTimeMillis();
                
                Object result = invocation.proceed();
                
                useTime = System.currentTimeMillis() - begin;
                logger.debug("~~~~~~~~ method process useTime:" + useTime + "~~~~~~~~");
                return result;
            }
        } finally {
            logger.debug("~~~~~~~~ leave AccessControlMethodInterceptor ~~~~~~~~");
        }
    }

    private boolean loginRequiredHandler() {
        /*AppLoginDevice appLoginDevice = (AppLoginDevice) session.getAttribute("appLoginDevice");
        if (null != appLoginDevice && null != appLoginDevice.getLoginUserId() && appLoginDevice.getLoginUserId() > 0) {
            return true;
        }*/
        return false;
    }

    private boolean hasPermissionHandler(String[] permissionArray) {
        //如果没有permission，则等同于loginRequired
        if (null == permissionArray || permissionArray.length < 1) {
            return this.loginRequiredHandler();
        }

        /*AppLoginDevice appLoginDevice = (AppLoginDevice) session.getAttribute("appLoginDevice");
        if (null != appLoginDevice && null != appLoginDevice.getLoginUserId() && appLoginDevice.getLoginUserId() > 0) {
            List<AppPermission> appPermissionList = (List<AppPermission>)session.getAttribute("appPermissionList");
        	//如果用户没有permission
            if (null == appPermissionList || appPermissionList.size() < 1) {
            	throw FoodException.returnException("000022");
            }
            Set<String> pSet = new HashSet<>();
            for (AppPermission ap : appPermissionList) {
                pSet.add(ap.getPermissionId());
            }
            boolean hasPer = true;
            for (String permission : permissionArray) {
                //只要有一个permission用户没有，返回false
                if (!pSet.contains(permission)) {
                	hasPer = false;
                }
            }
            if(hasPer){
            	return true;
            }else{
            	throw InsuranceException.returnException("000022");
            }
        }else{*/
        	throw TraceException.returnException("000021");
//        }
    }
}
